

import { GameBalance } from "../data/GameBalance";
import AudioManager from "../manager/audio_manager";
import DD from "../manager/dynamic_data_manager";
import MainManager from "../manager/main_manager";
import PoolManager from "../manager/pool_manager";
import StorageManager from "../manager/storage_manager";
import Enemy from "./Enemy";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Bullet extends cc.Component {

    @property(cc.Label)
    label: cc.Label = null;

    target: Enemy;
    speed: number = 400;
    atk: number = 5;
    id: number = 5
    spreadCount: number = 0;
    bulletSpeed: number = 30000;
    isSpreading: boolean = false;
    rb2d: cc.RigidBody
    direction: cc.Vec3
    life: number = 1;

    init(target, spreadCount = 0) {
        this.target = target; // 设置目标敌人
        this.spreadCount = spreadCount;
        this.node.setScale(.2, .2)
        if (target != null) {
            this.direction = this.target.node.position.sub(this.node.position).normalize();
        }
        // cc.log('额外rate：',(1+DD.instance.caculateAtkEtraRate()));
        this.atk = GameBalance.calculateSkillAtk(this.id.toString())
        cc.log('bullet',this.atk)
        this.life = DD.instance.peneCount
        // this.rb2d = this.getComponent(cc.RigidBody)
    }

    update(dt) {
        // if (!this.target || !this.target.node) {
        //     // this.node.destroy(); // 如果目标无效，销毁子弹
        //     return;
        // }
        if (!this.node) {
            return;
        }
        // this.timer+=dt*cc.director.getScheduler().getTimeScale()
        // 子弹朝目标移动
        // if (this.isSpreading) {

        let movement = this.direction.mul(this.speed * dt * cc.director.getScheduler().getTimeScale());
        this.node.position = this.node.position.add(movement);
        // }


        // // 检测是否到达目标
        // if (this.node.position.sub(this.target.node.position).mag() < 10) {
        //     this.attackTarget();

        // }
    }

    onCollisionEnter(other, self) {
        // cc.log('bullet 打击Enter');
        if (other.node.group === 'Enemy') {
            let enemyScript = other.getComponent(Enemy)
            // this.attackTarget(other.getComponent(Enemy));

            if (enemyScript) {
                if (StorageManager.instance.skills.includes("3")) {
                    let obj = PoolManager.instance.createObjectByName('explode', this.node.parent);
                    obj.setPosition(this.node.x, this.node.y)
                }
                enemyScript.takeDamage(this.atk); // 对敌人造成伤害
                this.life--;
                AudioManager.instance.playAudio('hitGround')
                if (this.spreadCount > 0) {
                    // 使用示例：假设原节点是 this.node
                    this.createCopies(this.node, StorageManager.instance.spreadCount, 10);  // 6 个复制体，均匀分布在半径为 100 的圆形上
                    // let newtarget = this.setNewTarget();

                    // if (newtarget != null) {
                    //     this.target = newtarget;
                    //     this.isSpreading = true;
                    //     const targetPosition = this.target.node.position;

                    //     const directionToTarget = cc.v2(targetPosition.x - this.node.position.x, targetPosition.y - this.node.position.y).normalize();

                    //     if (this.rb2d) {
                    //         this.rb2d.linearVelocity = cc.v2(0, 0);
                    //         const force = directionToTarget.mul(this.bulletSpeed); // 根据方向和力大小计算力向量
                    //         this.rb2d.applyForce(force, this.rb2d.getWorldCenter(), true); // 施加力
                    //     }
                    // }
                }

            }
            if (this.life <= 0) {
                PoolManager.instance.removeObject(this.node)
            }

            // this.spreadCount--;
            // if (this.spreadCount <= 0) {

            // }
        }
    }

    // 假设这个函数是用于创建并排列复制体
    createCopies(node, count, radius) {
        // 获取原节点的位置
        let originPosition = this.node.position;

        // 获取角度间隔
        let angleInterval = 360 / count;
        // 处理数量小于等于 4 的情况
        if (count <= 4) {
            // 计算每个位置的偏移
            let positions = [
                cc.v3(-1, 0), // 左上
                cc.v3(1, 0), // 右上
                cc.v3(0, 1), // 左下
                cc.v3(0, -1)  // 右下
            ];

            // 只使用前 count 个位置
            for (let i = 0; i < count; i++) {
                let bullet = PoolManager.instance.createObjectByName('bullet', this.node.parent);
                bullet.setPosition(node.x, node.y)
                let bulletScript = bullet.getComponent('Bullet');
                // let dir =  positions[i].sub(this.node.position).normalize()
                if (bulletScript) {
                    bulletScript.direction = positions[i];
                    bulletScript.init(null, 0); // 设置子弹的目标
                }
                // 设置复制体的位置
                // newNode.setPosition(positions[i]);
            }
        } else {
            for (let i = 0; i < count; i++) {
                // 创建一个新的节点（复制当前节点）

                let bullet = PoolManager.instance.createObjectByName('bullet', this.node.parent);


                // 计算当前复制体的角度（单位是度）
                let angle = i * angleInterval;

                // 将角度转换为弧度
                let radian = cc.misc.degreesToRadians(angle);

                // 计算新的位置
                let newX = originPosition.x + radius * Math.cos(radian);
                let newY = originPosition.y + radius * Math.sin(radian);
                let direction = bullet.position.sub(this.node.position).normalize();

                // 设置复制体的位置
                bullet.setPosition(cc.v2(newX, newY));
                let bulletScript = bullet.getComponent('Bullet');

                if (bulletScript) {
                    bulletScript.direction = direction;
                    bulletScript.init(null, 0); // 设置子弹的目标
                }
            }
        }

    }


    setNewTarget() {
        let minDistance = Infinity;
        let nearestEnemy = null;

        MainManager.instance.enemies.forEach(enemy => {
            if (enemy && enemy.node) {
                // 排除与当前目标相同的敌人
                if (enemy.globalId !== this.target.globalId) {
                    // 计算与当前敌人的距离
                    let distance = this.node.position.sub(enemy.node.position).mag();

                    // 如果距离更小，更新最近的敌人
                    if (distance < minDistance) {
                        minDistance = distance;
                        nearestEnemy = enemy;
                    }
                }
            }
        });

        // 返回最近的敌人
        console.log('Nearest enemy:', nearestEnemy);
        return nearestEnemy;
    }

    // update (dt) {}
}
